import React, {
  useState,
  useEffect,
  useRef,
  useMemo,
  useCallback,
} from "react";
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Row,
  Col,
  message,
  Divider,
  Tooltip,
} from "antd";
import styles from "../index.less";
import { auth } from "@/utils/auth";
import { history } from "umi";
import {
  ArrowUpOutlined,
  SearchOutlined,
  CloseOutlined,
  CheckOutlined,
  EditOutlined,
  PaperClipOutlined,
  HighlightOutlined,
} from "@ant-design/icons";
const { TextArea } = Input;
const { Option } = Select;

interface CopywritingResult {
  title: string;
  content: string;
}

const CopywritingTest: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const userId = auth.getUserId();

  // 续写
  const [inputTitle, setInputTitle] = useState<string | null>(null);
  const [inputValue, setInputValue] = useState("");
  const [continuationLoading, setContinuationLoading] = useState(false);

  // 编辑模式切换
  const [edit, setEdit] = useState(false);

  // 改写
  const [selection, setSelection] = useState({
    start: 0,
    end: 0,
    selectedText: "",
  });
  const [inputPosition, setInputPosition] = useState<{
    x: any;
    y: any;
  } | null>(null);
  const [inputValue2, setInputValue2] = useState("语气活泼");

  const [copywritingResult, setCopywritingResult] =
    useState<CopywritingResult | null>(null);
  const [adaptationText, setAdaptationText] = useState<string | null>(null);

  const [isDragging, setIsDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [adaptationLoading, setAdaptationLoading] = useState(false);

  const [recommendResult, setRecommendResult] = useState<any>(null);

  // 处理拖拽开始
  const handleMouseDown = (e: React.MouseEvent) => {
    if (inputPosition) {
      setIsDragging(true);
      setDragOffset({
        x: e.clientX - inputPosition.x,
        y: e.clientY - inputPosition.y,
      });
      e.preventDefault();
      e.stopPropagation();
    }
  };

  // 添加鼠标事件监听
  useEffect(() => {
    if (isDragging) {
      // 使用document级别的事件处理，以便在拖动过程中鼠标离开元素时也能继续跟踪
      const handleDocumentMouseMove = (e: MouseEvent) => {
        setInputPosition({
          x: e.clientX - dragOffset.x,
          y: e.clientY - dragOffset.y,
        });
      };

      const handleDocumentMouseUp = () => {
        setIsDragging(false);
      };

      document.addEventListener("mousemove", handleDocumentMouseMove);
      document.addEventListener("mouseup", handleDocumentMouseUp);

      return () => {
        document.removeEventListener("mousemove", handleDocumentMouseMove);
        document.removeEventListener("mouseup", handleDocumentMouseUp);
      };
    }
  }, [isDragging, dragOffset]);

  // 生成文案
  const handleGenerateCopy = async (values: any) => {
    try {
      setLoading(true);

      const response = await fetch("/agentai/content/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          ...values,
        }),
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          setCopywritingResult({
            ...result.data,
            content: result.data.content.replace(/\/n/g, "\n"),
          });
          message.success("文案生成成功");
        } else {
          message.error(result.message || "生成失败");
        }
      } else {
        message.error("生成失败");
      }
    } catch (error) {
      message.error("生成失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  const handleGenerateCopy2 = () => {
    const result = {
      code: 200,
      message: "文案生成成功",
      data: {
        title: "年轻人的第一台智能车：小米SU7",
        content:
          "还在为第一辆车纠结吗？来看看小米SU7，专为年轻而生！/n/n作为小米首款智能车型，SU7不仅延续了品牌一贯的高性价比，还带来了超多惊喜。外观设计简约时尚，流线型车身搭配多种潮流配色，开出去绝对吸睛！搭载最新智能驾驶系统，支持语音交互、自动泊车等功能，科技感满满，新手司机也能轻松上手。/n/n动力方面也同样优秀，强劲电机带来流畅加速体验，同时续航能力高达600公里，周末自驾游完全无压力。最棒的是，车内还配备了沉浸式音响和氛围灯，无论是通勤还是旅行，都能让每一段路程变成享受。/n/n关键是价格真的很友好！对于预算有限但追求品质的年轻人来说，小米SU7无疑是最佳选择。快来预约试驾吧，感受未来出行的魅力！",
        hashtag: [
          "#小米SU7",
          "#年轻人的第一辆车",
          "#智能汽车推荐",
          "#潮流座驾",
          "#性价比之王",
        ],
        createdAt: "2025-03-23T15:27:50",
        totalToken: 426,
      },
    };
    setCopywritingResult({
      ...result.data,
      content: result.data.content.replace(/\/n/g, "\n"),
    });
  };

  // 智能打标签
  const handleRecommend = async () => {
    const values = form.getFieldsValue();
    const response = await fetch("/agentai/content/assessment", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        userId,
        type: values.type,
        platform: values.platform,
        content: copywritingResult?.content || "",
      }),
    });

    if (response.status === 200) {
      const result = await response.json();
      setRecommendResult(result.data);
      form.setFieldsValue({
        tags: result.data?.tags
          ? result.data.tags.map((tag: string) => `#${tag}`).join("，")
          : "",
        recommendReason: result.data.recommendReason,
      });
    } else {
      message.error("推荐失败");
    }
  };

  const handleShow = (title: string) => {
    setInputTitle(title || "");
    setSelection({ start: 0, end: 0, selectedText: "" });
    setTimeout(() => {
      const ipt = document.getElementById("xx");
      ipt?.focus();
    }, 500);
  };

  const handlehide = () => {
    setInputTitle("");
    setInputValue("");
    setInputValue2("");
    setSelection({ start: 0, end: 0, selectedText: "" });
  };

  const handleEdit = (edit: boolean) => {
    if (adaptationLoading || inputTitle === "确认替换") {
      message.info("文案改写中，不可切换，请改写完成后再试。");
      return;
    }
    setEdit(edit);
    if (edit) {
      handlehide();
    }
  };

  const onEdit = (e: any) => {
    setCopywritingResult((prev) =>
      prev
        ? {
            ...prev,
            content: e.target.value,
          }
        : null
    );
  };

  // 续写
  const handleContinueWriting = async () => {
    try {
      setContinuationLoading(true);
      const values = form.getFieldsValue();
      const response = await fetch("/agentai/content/continuation", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          type: values.type,
          platform: values.platform,
          originalContent: copywritingResult?.content || "",
          description: inputValue,
          referenceContent: values.referenceContent,
        }),
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          // 更新文案内容，将续写的内容添加到原内容后面
          setCopywritingResult((prev) =>
            prev
              ? {
                  ...prev,
                  content: prev.content + "\n\n" + result.data.content,
                }
              : null
          );
          message.success("续写成功");
          handlehide();
        } else {
          message.error(result.message || "续写失败");
        }
      } else {
        message.error("续写失败");
      }
    } catch (error) {
      message.error("续写失败，请检查网络连接");
    } finally {
      setContinuationLoading(false);
    }
  };

  // 处理文本选中事件
  const handleMouseUp = useCallback(() => {
    const selection = window.getSelection();
    const selectedText = selection?.toString() || null;
    // console.log("selectedText", selectedText);

    if (
      selectedText &&
      selection &&
      selection.rangeCount > 0 &&
      selection.toString().trim() !== ""
    ) {
      const range = selection?.getRangeAt(0);

      const preSelectionRange = range?.cloneRange();
      preSelectionRange?.selectNodeContents(divRef.current);
      preSelectionRange?.setEnd(range.startContainer, range?.startOffset);
      const start = preSelectionRange?.toString().length;
      const end = start + selection.toString().length;
      setSelection({ start, end, selectedText });

      const rect = range?.getBoundingClientRect();
      if (rect) {
        setInputTitle("改写");
        setTimeout(() => {
          const ipt = document.getElementById("gx");
          ipt?.focus();
        }, 500);

        var maxX = window.innerWidth - 380;
        let currentx = rect.left + window.scrollX;
        setInputPosition({
          x: currentx > maxX ? maxX : currentx,
          y: rect.bottom + window.scrollY + 10,
        });
      }
    } else {
      // setInputPosition(null);
    }
  }, []);

  // 高亮文本,text是copywritingResult.content
  const highlightedText = useMemo(() => {
    const chars = [];
    let text = copywritingResult?.content || "";
    let currentIndex = 0;

    while (currentIndex < text.length) {
      // 检查当前字符和下一个字符是否是 \n
      if (text[currentIndex] === "\\" && text[currentIndex + 1] === "n") {
        chars.push(<br key={currentIndex} />); // 渲染为 <br> 标签
        currentIndex += 2; // 跳过 \ 和 n
      } else {
        const isHighlighted =
          currentIndex >= selection.start && currentIndex < selection.end;
        chars.push(
          <span
            key={currentIndex}
            style={{
              backgroundColor: isHighlighted ? "yellow" : "transparent",
            }}
          >
            {text[currentIndex]}
          </span>
        );
        currentIndex += 1;
      }
    }

    return chars;
  }, [copywritingResult?.content, selection]);

  // 改写
  const handleAdaptation = async () => {
    try {
      setAdaptationLoading(true);
      const values = form.getFieldsValue();
      const response = await fetch("/agentai/content/adaptation", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId,
          type: values.type,
          platform: values.platform,
          originalContent: copywritingResult?.content || "",
          contentToBeAdapted: selection?.selectedText || "",
          description: inputValue2,
          referenceContent: values.referenceContent,
        }),
      });

      if (response.status === 200) {
        const result = await response.json();
        if (result.code === 200) {
          setInputTitle("确认替换");
          setAdaptationText(result.data.content);
        } else {
          message.error(result.message || "改写失败");
        }
      } else {
        message.error("改写失败");
      }
    } catch (error) {
      message.error("改写失败，请检查网络连接");
    } finally {
      setAdaptationLoading(false);
    }
  };

  // 确认改写
  const handleAdaptationsure = () => {
    const { start, end } = selection;
    setCopywritingResult((prev) =>
      prev
        ? {
            ...prev,
            content:
              prev.content.slice(0, start) +
              adaptationText +
              prev.content.slice(end),
          }
        : null
    );
    message.success("改写成功");
    handlehide();
  };

  const divRef = useRef(null);
  return (
    <Row gutter={24}>
      <Col span={12}>
        <Card title="文案生成">
          <div className={styles.colcard}>
            <Form
              form={form}
              layout="horizontal"
              onFinish={handleGenerateCopy}
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 17 }}
              // initialValues={{
              //   type: "产品推销",
              //   platform: "小红书笔记",
              //   description:
              //     "请为我写一篇200-300字的产品推销文案，产品名称是小米SU7，目标人群是年轻人。",
              // }}
            >
              <Form.Item
                name="platform"
                label="媒体渠道"
                rules={[{ required: true, message: "请选择媒体渠道" }]}
              >
                <Select placeholder="请选择媒体渠道">
                  <Option value="小红书笔记">小红书笔记</Option>
                  <Option value="微信朋友圈">微信朋友圈</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="type"
                label="文案类型"
                rules={[{ required: true, message: "请选择文案类型" }]}
              >
                <Select placeholder="请选择文案类型">
                  <Option value="产品推销">产品推销</Option>
                  <Option value="个人品牌建设">个人品牌建设</Option>
                  <Option value="生活分享">生活分享</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="description"
                label="文案内容描述"
                rules={[
                  { required: true, message: "请输入文案内容描述" },
                  { max: 300, message: "不能超过300个字" },
                ]}
              >
                <TextArea
                  rows={6}
                  placeholder="请为我写一篇200-300字的产品推销文案，产品名称是[产品名称]，目标人群是[目标人群]（如：年轻女性、职场人士等）。文案需要突出产品的核心卖点：[核心卖点]，文章风格亲和力强，带有轻松的促销氛围"
                />
              </Form.Item>

              <Form.Item
                name="referenceContent"
                label="参考文案"
                rules={[{ max: 500, message: "不能超过500个字" }]}
              >
                <TextArea
                  rows={8}
                  placeholder="监管要求与数据隐私： 医疗AI创业也面临严格的监管和伦理要求。首先，取得医疗器械审批认证是进入市场的前提。各国监管机构对AI作为软件医疗器械（SaMD）的审核日趋严格，需要充分的临床试验数据证明安全有效。在美国，IDx-DR通过了FDA De Novo途径成为首个自治诊断AI​创业公司需要建立清晰的数据使用政策，与医疗机构签订数据合作协议并保护网络安全，以赢得信任。最后，从伦理上讲，让患者知情AI的介入也很重要，监管可能要求在报告或结果界面注明“此结果由AI辅助生成，需由医生确认”等告示，以免患者盲目信赖或产生误解。"
                />
              </Form.Item>

              <Form.Item
                style={{ textAlign: "center" }}
                wrapperCol={{ span: 24 }}
              >
                <Button
                  type="primary"
                  htmlType="submit"
                  style={{ width: "60%" }}
                  loading={loading}
                  block
                >
                  生成文案
                </Button>
              </Form.Item>
            </Form>
          </div>
        </Card>
      </Col>
      <Col span={12}>
        <Card title="生成结果">
          <div className={styles.colcard}>
            {copywritingResult ? (
              <>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                  }}
                >
                  <h3>{copywritingResult.title}</h3>
                  <div>
                    <Tooltip title="文案续写">
                      <HighlightOutlined
                        onClick={() => handleShow("续写")}
                        style={{ marginRight: 10, color: "grey" }}
                      />
                    </Tooltip>
                    <Tooltip title={edit ? "切换为改写状态" : "切换为编辑状态"}>
                      <EditOutlined
                        onClick={() => handleEdit(!edit)}
                        style={{ marginRight: 10, color: "grey" }}
                      />
                    </Tooltip>
                  </div>
                </div>

                <div style={{ marginBottom: 16 }}>
                  {edit ? (
                    <TextArea
                      ref={divRef}
                      value={copywritingResult?.content}
                      // autoSize
                      onChange={onEdit}
                      style={{
                        height: "calc(100vh - 520px)",
                        // backgroundColor: "pink",
                      }}
                    />
                  ) : (
                    <div
                      ref={divRef}
                      style={{
                        whiteSpace: "pre-wrap",
                        userSelect: "text",
                        backgroundColor: "#f5f5f5",
                        padding: "12px",
                        borderRadius: "4px",
                        fontSize: "14px",
                        lineHeight: "1.8",
                        cursor: "text",
                        transition: "background-color 0.3s",
                        border: "1px solid transparent",
                        height: "calc(100vh - 520px)",
                        overflow: "auto",
                        scrollbarWidth: "none",
                      }}
                      // onMouseDown={() => {
                      //   const selection = window.getSelection();
                      //   if (selection?.toString()) {
                      //     selection.removeAllRanges();
                      //   }
                      // }}
                      onMouseUp={handleMouseUp}
                    >
                      {highlightedText}
                      {/* {highlightedText?.replace(/\\n/g, "\n")} */}
                    </div>
                  )}
                </div>

                <Divider orientation="left" plain>
                  <Tooltip title="智能推荐">
                    <PaperClipOutlined
                      onClick={handleRecommend}
                      style={{ marginLeft: 0, color: "grey" }}
                    />
                  </Tooltip>
                </Divider>
                <div>
                  <div className={styles.tagsBox}>
                    <span
                      style={{
                        width: 80,
                        color: "#000000E0",
                      }}
                    >
                      标签
                    </span>
                    <Input
                      placeholder="请输入标签"
                      value={
                        recommendResult?.tags
                          ? recommendResult.tags
                              .map((tag: string) => `#${tag}`)
                              .join("，")
                          : ""
                      }
                    />
                  </div>
                  <div className={styles.tagsBox}>
                    <span
                      style={{
                        width: 80,
                        color: "#000000E0",
                      }}
                    >
                      推荐理由
                    </span>
                    <Input
                      placeholder="请输入推荐理由"
                      value={recommendResult?.recommendReason}
                    />
                  </div>
                </div>
              </>
            ) : (
              <div style={{ textAlign: "center", color: "#999" }}>
                点击生成按钮开始生成文案
              </div>
            )}
          </div>

          {inputTitle === "确认替换" && inputPosition && (
            <div
              style={{
                position: "fixed",
                left: inputPosition.x,
                top: inputPosition.y,
                zIndex: 100,
                width: 350,
                border: "1px solid #ddd",
                padding: 10,
                borderRadius: 10,
                boxShadow: "0 0 10px grey",
                background: "white",
                maxHeight: 250,
                overflow: "auto",
                scrollbarWidth: "none",
              }}
            >
              <div>
                <div
                  style={{
                    backgroundColor: "#f5f5f5",
                    padding: "8px",
                    borderRadius: "4px",
                    fontSize: "14px",
                    cursor: "text",
                    marginBottom: 10,
                  }}
                >
                  <h4>原文案</h4>
                  <span style={{ color: "#777" }}>
                    {selection?.selectedText}
                  </span>
                </div>
                <div
                  style={{
                    backgroundColor: "#f5f5f5",
                    padding: "8px",
                    borderRadius: "4px",
                    fontSize: "14px",
                    cursor: "text",
                    marginBottom: 10,
                  }}
                >
                  <h4>改写后</h4>
                  <span style={{ color: "#777" }}>{adaptationText}</span>
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <Tooltip title="取消">
                  <Button
                    color="default"
                    variant="filled"
                    shape="circle"
                    icon={<CloseOutlined />}
                    onClick={handlehide}
                    style={{ marginRight: 5 }}
                  />
                </Tooltip>
                <Tooltip title="确认改写">
                  <Button
                    color="default"
                    variant="filled"
                    shape="circle"
                    icon={<CheckOutlined />}
                    onClick={handleAdaptationsure}
                  />
                </Tooltip>
              </div>
            </div>
          )}

          {inputTitle === "改写" && inputPosition && (
            <div
              style={{
                position: "fixed",
                left: inputPosition.x,
                top: inputPosition.y,
                zIndex: 100,
                width: 350,
                display: "flex",
                justifyContent: "space-between",
                border: "1px solid #ddd",
                padding: 5,
                borderRadius: 10,
                boxShadow: "0 0 10px grey",
                background: "white",
              }}
            >
              <Input.TextArea
                id="gx"
                placeholder="请输入改写内容"
                autoSize
                style={{ marginRight: 10, border: "none" }}
                value={inputValue2}
                onChange={(e) => setInputValue2(e.target.value)}
              />
              <Tooltip title="提交">
                <Button
                  color="default"
                  variant="filled"
                  shape="circle"
                  icon={<ArrowUpOutlined />}
                  onClick={handleAdaptation}
                  style={{ marginRight: 5 }}
                  loading={adaptationLoading}
                />
              </Tooltip>
              <Tooltip title="取消">
                <Button
                  color="default"
                  variant="filled"
                  shape="circle"
                  icon={<CloseOutlined />}
                  onClick={handlehide}
                  disabled={adaptationLoading}
                />
              </Tooltip>
            </div>
          )}

          {inputTitle === "续写" && (
            <div
              style={{
                position: "fixed",
                top: 240,
                right: 130,
                zIndex: 100,
                width: 350,
                display: "flex",
                justifyContent: "space-between",
                border: "1px solid #ddd",
                padding: 5,
                borderRadius: 10,
                boxShadow: "0 0 10px grey",
                background: "white",
              }}
            >
              <Input.TextArea
                id="xx"
                placeholder="请输入续写内容"
                autoSize
                style={{ marginRight: 10, border: "none" }}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
              />
              <Tooltip title="提交">
                <Button
                  color="default"
                  variant="filled"
                  shape="circle"
                  icon={<ArrowUpOutlined />}
                  onClick={handleContinueWriting}
                  style={{ marginRight: 5 }}
                  loading={continuationLoading}
                />
              </Tooltip>
              <Tooltip title="取消">
                <Button
                  color="default"
                  variant="filled"
                  shape="circle"
                  icon={<CloseOutlined />}
                  onClick={handlehide}
                  disabled={continuationLoading}
                />
              </Tooltip>
            </div>
          )}
        </Card>
      </Col>
    </Row>
  );
};

export default CopywritingTest;
